/*
 * ContribuyentesImpuestosVerFrame.java
 *
 * Created on 24 de abril de 2008, 06:49 PM
 */
package org.contabilidad.morosidad.inicial;



import org.mybeans.Sesion;
import org.mybeans.ContribuyentesBeans;
import org.mybeans.VigenciasExpiradasBeans;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.contribuyentes.ContribuyentesBusquedaFrame;

/**
 *
 * @author  avbravo
 */
public class MorosidadInicialContribuyentesConsultarFrame extends javax.swing.JFrame {

    Sesion sesion;
    ContribuyentesBeans contribuyentesBeans;
    VigenciasExpiradasBeans vigenciasExpiradasBeans;
    int fila = -1;
    DefaultTableModel modelo;
boolean focoBuscar = false;
    /** Creates new form ContribuyentesImpuestosVerFrame */
    public MorosidadInicialContribuyentesConsultarFrame() {
        initComponents();
        sesion = new Sesion();
        contribuyentesBeans = new ContribuyentesBeans();
      vigenciasExpiradasBeans = new VigenciasExpiradasBeans();
        jTextFieldTotalAdeudado.setText("");

          /*
         * Fondo
       */

		 
		 
		 

		jPanel3.setOpaque(false);
		setContentPane(jPanel3 );
/*
 * fondo
 */
           if (sesion.getCedulaContribuyente() == null || sesion.getCedulaContribuyente().equals(""))
        {

        }
         else{
            jTextFieldCedula.setText(sesion.getCedulaContribuyente());
            ValidarCedula();
         }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCedula = new javax.swing.JTextField();
        jTextFieldContribuyente = new javax.swing.JTextField();
        jButtonBuscarContribuyentes = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldTotalAdeudado = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Morosidad Inicial de Contribuyentes");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Cedula");

        jLabel2.setText("Contribuyente");

        jTextFieldCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCedulaActionPerformed(evt);
            }
        });

        jTextFieldContribuyente.setEditable(false);

        jButtonBuscarContribuyentes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/search.png"))); // NOI18N
        jButtonBuscarContribuyentes.setToolTipText("Buscar");
        jButtonBuscarContribuyentes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarContribuyentesActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Cerrar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "codigo", "Regimen", "Inicial", "Actual", "Fecha", "Año"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                true, false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(5).setResizable(false);

        jLabel3.setText("Total Adeudado");

        jTextFieldTotalAdeudado.setEditable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonBuscarContribuyentes, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldContribuyente, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 702, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(60, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(287, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(jTextFieldTotalAdeudado, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(262, 262, 262))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBuscarContribuyentes, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldContribuyente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldTotalAdeudado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonBuscarContribuyentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarContribuyentesActionPerformed
 
    ContribuyentesBusquedaFrame contribuyentesBusquedaFrame = new ContribuyentesBusquedaFrame();
    contribuyentesBusquedaFrame.setLocationRelativeTo(null);
    contribuyentesBusquedaFrame.setVisible(true);
focoBuscar = true;
}//GEN-LAST:event_jButtonBuscarContribuyentesActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed
 
    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jTextFieldCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCedulaActionPerformed
ValidarCedula();
    
}//GEN-LAST:event_jTextFieldCedulaActionPerformed

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
    if (focoBuscar){
         Limpiar();
    CargarContribuyentes();
    CargarMorosidadInicial();
    }
     focoBuscar = false;
}//GEN-LAST:event_formWindowGainedFocus

private void ValidarCedula(){
    try {
        Limpiar();
        String cedula = this.jTextFieldCedula.getText();
        sesion.setCedulaContribuyente(jTextFieldCedula.getText());
        if (cedula == null || cedula.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese la cedula del contribuyente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String sqlquery = "select * from contribuyentes where idmunicipio = ? and cedula = ?";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, sesion.getIdmunicipio());
        psquery.setString(2, cedula);
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();
        if (x == 0) {
            JOptionPane.showMessageDialog(this, "No existen registros de contribuyentes con esa cedula", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String activo = rs.getString("activo");
        if (activo.equals("no")) {
            JOptionPane.showMessageDialog(this, "Este registro esta inactivo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String contribuyente = rs.getString("contribuyente");

        if (contribuyente == null || contribuyente.equals("")) {
            JOptionPane.showMessageDialog(this, "El contribuyente esta en blanco", "Mensaje", JOptionPane.WARNING_MESSAGE);
            return;
        }
        contribuyentesBeans.setCedula(cedula);
        contribuyentesBeans.setContribuyente(contribuyente);
        this.jTextFieldCedula.setText(contribuyentesBeans.getCedula());
        this.jTextFieldContribuyente.setText(contribuyentesBeans.getContribuyente());
        CargarMorosidadInicial();
        repaint();

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MorosidadInicialContribuyentesConsultarFrame().setVisible(true);
            }
        });
    }

    public void CargarContribuyentes() {
        try {
            // ContribuyentesBeans contribuyentesBeans = new ContribuyentesBeans();
            if (contribuyentesBeans.getActivo().equals("no")) {
                JOptionPane.showMessageDialog(this, "Este registro esta inactivo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            this.jTextFieldCedula.setText(contribuyentesBeans.getCedula());
            sesion.setCedulaContribuyente(jTextFieldCedula.getText());
            this.jTextFieldContribuyente.setText(contribuyentesBeans.getContribuyente());

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void CargarMorosidadInicial() {
        try {
            Limpiar();
            String cedula = jTextFieldCedula.getText();
             String sql = "select vigenciasexpiradas.*, regimen.regimen from  vigenciasexpiradas, regimen where vigenciasexpiradas.idmunicipio=? and vigenciasexpiradas.id =? and vigenciasexpiradas.tipoid ='contribuyentes' and vigenciasexpiradas.activo='si' and vigenciasexpiradas.idregimen = regimen.idregimen and regimen.idmunicipio=? and regimen.activo='si'";
             if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            PreparedStatement psquery = sesion.con.prepareStatement(sql);
            psquery.setObject(1, sesion.getIdmunicipio());
            psquery.setObject(2, cedula);
            psquery.setObject(3, sesion.getIdmunicipio());
            ResultSet rs = psquery.executeQuery();

            modelo = new DefaultTableModel();
            // Creamos las columnas.
            modelo.addColumn("codigo");
            modelo.addColumn("regimen");
            modelo.addColumn("inicial");
            modelo.addColumn("actual");
            modelo.addColumn("fecha");
            modelo.addColumn("año");
Double totaladeudado = 0.0;
// Bucle para cada resultado en la consulta
            while (rs.next()) {
                // Se crea un array que será una de las filas de la tabla.
                Object[] fila = new Object[7]; // Hay tres columnas en la tabla

                fila[0] = rs.getString("idregimen");
                fila[1] = rs.getString("regimen");
                fila[2] = rs.getString("morosidadinicial");
                fila[3] = rs.getString("morosidadactual");
                totaladeudado += rs.getDouble("morosidadactual");
                Date fecha = rs.getDate("fecha");
                Format formatter;
                formatter = new SimpleDateFormat("dd/MM/yyyy");
                String s = formatter.format(fecha);
                fila[4] = s;
                fila[5]= rs.getInt("anio");
                modelo.addRow(fila);

            }
jTextFieldTotalAdeudado.setText(String.valueOf(totaladeudado));
            this.jTable1.setModel(modelo);
            jTable1.setVisible(true);

            this.jTable1.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {

                    fila = jTable1.rowAtPoint(e.getPoint());
                    int columna = jTable1.columnAtPoint(e.getPoint());
                    if ((fila > -1) && (columna > -1)) {
                        String idRegimen = String.valueOf(jTable1.getValueAt(fila, 0));
                        String regimen = String.valueOf(jTable1.getValueAt(fila, 1));
                        String SMorosidadInicial = String.valueOf(jTable1.getValueAt(fila, 2));
                        Double morosidadInicial = Double.parseDouble(SMorosidadInicial);
                        String SMorosidadActual = String.valueOf(jTable1.getValueAt(fila, 3));
                        Double morosidadActual = Double.valueOf(SMorosidadActual);
                        String fecha = String.valueOf(jTable1.getValueAt(fila, 4));
                         vigenciasExpiradasBeans.setIdRegimen(idRegimen);
                        vigenciasExpiradasBeans.setRegimen(regimen);
                        vigenciasExpiradasBeans.setMorosidadInicial(morosidadInicial);
                        vigenciasExpiradasBeans.setMorosidadActual(morosidadActual);
                        


                    }
                }
            });
            TableColumn column = jTable1.getColumnModel().getColumn(1);
            column.setPreferredWidth(250);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    private void Limpiar() {

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscarContribuyentes;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldCedula;
    private javax.swing.JTextField jTextFieldContribuyente;
    private javax.swing.JTextField jTextFieldTotalAdeudado;
    // End of variables declaration//GEN-END:variables
}
